package cn.kmbeast.service.impl;

import cn.kmbeast.mapper.HealthModelConfigMapper;
import cn.kmbeast.mapper.UserHealthMapper;
import cn.kmbeast.pojo.api.ApiResult;
import cn.kmbeast.pojo.api.Result;
import cn.kmbeast.pojo.dto.query.base.QueryDto;
import cn.kmbeast.pojo.dto.query.extend.UserHealthQueryDto;
import cn.kmbeast.pojo.em.IsReadEnum;
import cn.kmbeast.pojo.em.MessageType;
import cn.kmbeast.pojo.entity.HealthModelConfig;
import cn.kmbeast.pojo.entity.Message;
import cn.kmbeast.pojo.entity.UserHealth;
import cn.kmbeast.pojo.vo.ChartVO;
import cn.kmbeast.pojo.vo.UserHealthVO;
import cn.kmbeast.service.MessageService;
import cn.kmbeast.service.UserHealthService;
import cn.kmbeast.utils.DateUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserHealthServiceImpl implements UserHealthService {

    @Resource
    private UserHealthMapper userHealthMapper;
    @Resource
    private HealthModelConfigMapper healthModelConfigMapper;
    @Resource
    private MessageService messageService;



    @Override
    public Result<Void> save(UserHealth userHealth) {
        userHealth.setCreateTime(LocalDateTime.now());
        //对传入的指标进行检查 是否需要提醒用户
        ExceptionNotification(userHealth);
        int rs =  userHealthMapper.save(userHealth);
        if (rs == 0){
            return ApiResult.error("插入失败");
        }else{
            return ApiResult.success();
        }
    }

    /**
     * 检查用户的输入值 和 正常范围比较 异常则直接返回给用户通知
     * @param userHealth
     */
    private void ExceptionNotification(UserHealth userHealth) {
        // 用户的指标超出正常范围则通知用户
        Integer healthModelConfigId = userHealth.getHealthModelConfigId();
        HealthModelConfig healthModelConfig = healthModelConfigMapper.selectByPrimaryKey(healthModelConfigId);
        String valueRange = healthModelConfig.getValueRange();
        valueRange = valueRange.replace("[", "").replace("]", "");
        String[] split = valueRange.split(",");
        int value = Integer.parseInt(userHealth.getValue());
        //查看value 是否在spilt 范围内

        if (  !(value > Integer.parseInt(split[0]) && value < Integer.parseInt(split[1])) ){
            Message message = new Message();
            message.setMessageType(MessageType.DATA_MESSAGE.getType());
            message.setIsRead(IsReadEnum.READ_NO.getStatus());
            message.setReceiverId(userHealth.getUserId());
            message.setContent("您的"+healthModelConfig.getName() +"指标超出正常范围，请及时关注");
            message.setCreateTime(LocalDateTime.now());
            messageService.dataWordSave(Collections.singletonList(message));
        }
    }

    @Override
    public Result<Void> batchDelete(List<Long> ids) {
        int rs =  userHealthMapper.batchDelete(ids);
        if (rs != 0){
            return ApiResult.success();
        }else {
            return ApiResult.error("删除失败");
        }
    }

    @Override
    public Result<Void> update(UserHealth userHealth) {
        int rs = userHealthMapper.update(userHealth);
        if (rs != 0){
            return ApiResult.success();
        }else {
            return ApiResult.success();
        }
    }

    @Override
    public Result<List<UserHealthVO>> query(UserHealthQueryDto userHealthQueryDto) {
        List<UserHealthVO> rs = userHealthMapper.query(userHealthQueryDto);

        //按条件查询  返回查询的总数
        Integer totalCount = userHealthMapper.queryCount(userHealthQueryDto);

        if (rs != null && !rs.isEmpty()){
           return ApiResult.success(rs,totalCount);
        }else {
            return ApiResult.error("查询为空");
        }
    }

    /**
     * 按照天数的 时间段进行数据的统计
     * @param day
     * @return
     */
    @Override
    public Result<List<ChartVO>> daysQuery(Integer day) {
        //天数转换为时间段
        QueryDto queryDto = DateUtil.startAndEndTime(day);
        UserHealthQueryDto userHealthQueryDto = new UserHealthQueryDto();
        userHealthQueryDto.setStartTime(queryDto.getStartTime());
        userHealthQueryDto.setEndTime(queryDto.getEndTime());
        //按照条件查询
        List<UserHealthVO> userHealthVOS = userHealthMapper.query(userHealthQueryDto);
        List<LocalDateTime> localDateTimes = userHealthVOS
                .stream()
                .map(healthVO -> healthVO
                        .getCreateTime()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime())
                .collect(Collectors.toList());
        List<ChartVO> chartVOS = DateUtil.countDatesWithinRange(day, localDateTimes);
        return ApiResult.success(chartVOS);
    }
}
